#include "writepostdialog.h"
#include "ui_writepostdialog.h"

#include "flowcontroler.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QtDebug>

WritePostDialog::WritePostDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WritePostDialog)
{
    ui->setupUi(this);
    setWindowTitle("发帖");

    connect(FlowControler::Interface, &XInterface::postFinished, this, [ = ](int ret)
    {
        if(ret == NoError)
        {
            QMessageBox::information(this, "提示", "帖子已发布，等待管理员审核！");
            accept();

        }
        else
        {
            QMessageBox::warning(this, "警告", "发布失败" + FlowControler::Interface->getLastErrorString());
        }

    });
}

WritePostDialog::~WritePostDialog()
{
    delete ui;
}

void WritePostDialog::on_btnPost_clicked()
{
    QString title = ui->lineEdit->text();
    QString content = ui->textEdit->toPlainText();

    Core::Post post;
    post.userId = FlowControler::Interface->getCurrentUser()->id;
    post.title = title;
    post.content = content;
    post.pixSize = size_t(m_pix_buf.size());

    FlowControler::Interface->post(post);
    if(post.pixSize > 0)
    {
        FlowControler::Interface->m_pix_buf = m_pix_buf;
    }
}

void WritePostDialog::on_btnCancel_clicked()
{
    reject();
}

void WritePostDialog::on_btnPostPix_clicked()
{
    //上传图片
    QString filePath = QFileDialog::getOpenFileName(nullptr, "选择图片", "", "Images (*.png *.jpg)");
    if (!filePath.isEmpty())
    {
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly))
        {
            m_pix_buf = file.readAll();
            file.close();
            qDebug() << "图片已成功读取并存储为 QByteArray，大小为:" << m_pix_buf.size() << "字节";
        }
        else
        {
            qDebug() << "无法打开文件:" << filePath;
        }
    }
}
